<template>
  <div class="chat-container">
    <button @click="onClick">
      登录1
    </button>
    <!-- 消息展示区域 -->
    <div class="messages" ref="messagesContainer">
      <div v-for="(message, index) in messages" :key="index" class="message-item">
        <!-- 用户消息 -->
        <div v-if="message.role === 'user'" class="user-message">
          <div class="bubble">{{ message.content }}</div>
          <div class="avatar">👤</div>
        </div>
        
        <!-- AI消息 -->
        <div v-else class="ai-message">
          <div class="avatar">🤖</div>
          <div class="bubble">
            <div v-if="message.loading" class="loading">
              <span class="dot"></span>
              <span class="dot"></span>
              <span class="dot"></span>
            </div>
            <template v-else>
              <div v-html="message.content"></div>
            </template>
          </div>
        </div>
      </div>
    </div>

    <!-- 输入区域 -->
    <div class="input-area">
      <input
        v-model="inputText"
        @keyup.enter="sendMessage"
        placeholder="请输入您的问题..."
        :disabled="isLoading"
      />
      <button @click="sendMessage('zhinengt')" :disabled="!inputText || isLoading">
        {{ isLoading ? '生成中...' : '发送智能体' }}
      </button>
      <button @click="sendMessage('houduan')" :disabled="!inputText || isLoading">
        {{ isLoading ? '生成中...' : '发送后端' }}
      </button>
    </div>
  </div>
</template>

<script>
export default {
  name: 'ChatPage',
  data() {
    return {
      messages: [],
      inputText: '',
      isLoading: false,
      requestId: this.generateRequestId(), // 初始化时生成唯一requestId
    }
  },
  methods: {
     // 生成符合要求的requestId（时间戳+6位随机数）
     generateRequestId() {
      const timestamp = Date.now().toString();
      const random = Math.floor(100000 + Math.random() * 900000).toString();
      return timestamp + random;
    },
    // 生成符合要求的dialogId（精确时间+6位随机数）
    generateDialogId() {
      const now = new Date();
      const timePart = [
        now.getFullYear(),
        String(now.getMonth() + 1).padStart(2, '0'),
        String(now.getDate()).padStart(2, '0'),
        String(now.getHours()).padStart(2, '0'),
        String(now.getMinutes()).padStart(2, '0'),
        String(now.getSeconds()).padStart(2, '0'),
        String(now.getMilliseconds()).padStart(3, '0')
      ].join('');
      
      const random = Math.floor(100000 + Math.random() * 900000).toString();
      return timePart + random;
    },
    // 构建请求 URL
    buildRequestUrl() {
      return `/neibu/ai/forward`;
      // return `/AIapi/zjeop/rest/zjtest/agent/stdwk/8d2429fddf224ffea4a4f63bbe8683df?timestamp=${Date.now()}`;
    },
    // 构建请求体
    buildRequestBody() {
      return {
        keyword: this.inputText.trim(),  // 修正为当前输入内容
        requestId: this.requestId,       // 使用初始化生成的requestId
        dialogId: this.generateDialogId() // 每次生成新的dialogId
      };
    },
    // 构建请求头
    buildRequestHeaders() {
      return {
        'AuthToken': '03cab73430754cffbf489fc57aba5563',
        'X-APP-ID': '57d9b9c282e8a1b55995e25aafde7438',
        'X-APP-KEY': '3d2924f760942daae26543dc53fd41ac',
        'Content-Type': 'application/json',
        // 'Accept': '*/*',
        // 'Accept-Encoding': 'identity', // 明确告诉服务器不要压缩响应数据
        // 'Cache-Control': 'no-cache',
        // 'Pragma': 'no-cache',

        'authorization':localStorage.getItem('tokenValue')
      };
    },
    async sendMessage(name) {
      if (!this.inputText.trim()) return

          
      
      // 添加用户消息
      this.messages.push({
        role: 'user',
        content: this.inputText.trim()
      })
      
      // 添加AI的加载状态消息
      const aiMessage = {
        role: 'ai',
        content: '',
        loading: true
      }
      this.messages.push(aiMessage)
      
      
      // const question = this.inputText


      try {
        const requestBody = this.buildRequestBody();
        this.isLoading = true
        let url = ''
        if(name == 'zhinengt'){
          url='/AIapi/zjeop/rest/zjtest/agent/stdwk/8d2429fddf224ffea4a4f63bbe8683df'
        }else if(name == 'houduan'){
          // url = `/neibu/ai/forward?${new URLSearchParams(requestBody)}`
          url = `/neibu/ai/forward`
        }

        // const url = this.buildRequestUrl();
        const headers = this.buildRequestHeaders();
        const response = await fetch(url, {
        // const response = await fetch(`${url}?${new URLSearchParams(requestBody)}`, {
          method: name == 'zhinengt'?'post':'get',
          // method: 'post',
          headers,
          body: name == 'zhinengt'? JSON.stringify(requestBody): undefined,
          // body: JSON.stringify(requestBody),
          cache: 'no-cache'
        });
        // 问之后清空输入框1
        this.inputText = '';


        if (!response.ok) {
          throw new Error(`HTTP error! status: ${response.status}`);
        }

        const reader = response.body.getReader();
        const decoder = new TextDecoder('utf-8');
        this.responseData = '';
        let buffer = ''; // 用于缓存未解析的流数据

        while (true) {
          const { done, value } = await reader.read();
          if (done) {
            // 处理最后可能残留的数据
            if (buffer.trim()) {
              this.parseSSEData(buffer);
              buffer = '';
            }
            break;
          }

          // 解码并追加到缓冲区
          buffer += decoder.decode(value, { stream: true });

          // 按 SSE 格式分割数据（以 \n\n 为分隔符）
          const parts = buffer.split('\n\n');
          // 最后一个部分可能是不完整的，保留在缓冲区中
          buffer = parts.pop() || '';

          // 解析每条完整消息
          parts.forEach(part => {
            this.parseSSEData(part);
          });
          aiMessage.content = this.responseData;  // 每次更新内容
          this.$forceUpdate();                    // 强制更新视图
          this.scrollToBottom();
          aiMessage.loading = false
        }
      } catch (error) {
        aiMessage.content = '回答生成失败，请稍后再试1';
        aiMessage.loading = false;
        console.log('error',error);
      } finally {
        this.isLoading = false;
        this.scrollToBottom();
      }

    },

    // 新增方法：解析 SSE 格式数据
    parseSSEData(rawData) {
      // 按行分割
      const lines = rawData.split('\n');
      let data = '';
      
      lines.forEach(line => {
        if (line.startsWith('data:')) {
          // 提取 data 字段内容（去除前缀和首尾空格）
          const content = line.replace(/^data:\s*/, '').trim();
          
          // 剔除不需要的字段（CALLBACK#、attachment#[]#attachment、source#）
          const filteredContent = content
            .replace(/CALLBACK#.*?#CALLBACK/g, '') // 非贪婪匹配，删除 CALLBACK# 包裹的内容
            .replace(/attachment#.*?#attachment/g, '') // 删除固定字符串
            .replace(/source#.*?#source/g, ''); // 非贪婪匹配，删除 source# 包裹的内容

          data += filteredContent;
        }
        // 忽略其他字段（如 event、id 等）
      });

      if (data) {
        try {
          // 如果数据是 JSON，可以解析
          const parsedData = JSON.parse(data);
          this.responseData += JSON.stringify(parsedData, null, 2);
        } catch (e) {
          // 非 JSON 数据直接追加（已过滤无关内容）
          this.responseData += data;
        }
        // 触发界面更新
        this.$forceUpdate();
      }
    },
    
    // 自动滚动到底部
    scrollToBottom() {
      this.$nextTick(() => {
        const container = this.$refs.messagesContainer
        container.scrollTop = container.scrollHeight
      })
    },
    onClick(){
      // 清空token
      localStorage.removeItem('tokenValue');
    }
  }
}
</script>

<style scoped>
.chat-container {
  max-width: 800px;
  margin: 0 auto;
  height: 100vh;
  display: flex;
  flex-direction: column;
}

.messages {
  flex: 1;
  padding: 20px;
  overflow-y: auto;
  background: #f5f5f5;
}

.message-item {
  margin: 15px 0;
}

.user-message {
  display: flex;
  justify-content: flex-end;
  align-items: center;
  gap: 10px;
}

.ai-message {
  display: flex;
  justify-content: flex-start;
  /* align-items: center; */
  gap: 10px;
}

.avatar {
  width: 40px;
  height: 40px;
  border-radius: 50%;
  background: #fff;
  display: flex;
  align-items: center;
  justify-content: center;
  box-shadow: 0 2px 5px rgba(0,0,0,0.1);
}

.bubble {
  max-width: 70%;
  padding: 12px 18px;
  border-radius: 15px;
  line-height: 1.5;
  overflow-wrap: break-word;
}

.user-message .bubble {
  background: #007bff;
  color: white;
  border-radius: 15px 15px 0 15px;
}

.ai-message .bubble {
  background: white;
  color: #333;
  box-shadow: 0 2px 5px rgba(0,0,0,0.1);
  border-radius: 15px 15px 15px 0;
}

.input-area {
  padding: 20px;
  background: #fff;
  box-shadow: 0 -2px 10px rgba(0,0,0,0.05);
  display: flex;
  gap: 10px;
}

input {
  flex: 1;
  padding: 12px;
  border: 1px solid #ddd;
  border-radius: 25px;
  outline: none;
}

button {
  padding: 12px 25px;
  background: #007bff;
  color: white;
  border: none;
  border-radius: 25px;
  cursor: pointer;
  transition: opacity 0.3s;
}

button:disabled {
  background: #cccccc;
  cursor: not-allowed;
}

.loading {
  display: flex;
  gap: 4px;
  padding: 8px 0;
}

.dot {
  width: 8px;
  height: 8px;
  background: #ddd;
  border-radius: 50%;
  animation: bounce 1.4s infinite ease-in-out;
}

.dot:nth-child(2) {
  animation-delay: 0.2s;
}

.dot:nth-child(3) {
  animation-delay: 0.4s;
}

@keyframes bounce {
  0%, 80%, 100% { 
    transform: translateY(0);
  }
  40% {
    transform: translateY(-6px);
  }
}
</style>